//
//  MYNewsShopOrderDetailsBaseVC.m
//  MuYing
//
//  Created by tbb on 2020/3/11.
//  Copyright © 2020 TBB. All rights reserved.
//

#import "MYNewsShopOrderDetailsBaseVC.h"
#import "YQOrderDetailsHeaderView.h"
#import "YQOrderDetailsBottonView.h"
#import "OrderEvaViewController.h"
#import "YQGoodsOrderDetailsModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OrderEvaViewController.h"
#import <WXApi.h>
@interface MYNewsShopOrderDetailsBaseVC ()<YQOrderDetailsBottonViewDelegate>
@property (nonatomic, strong) YQOrderDetailsHeaderView * headerView;
@property (nonatomic, strong) YQOrderDetailsBottonView * bottonView;
@property (nonatomic,retain) NSMutableDictionary *payParameters;
@property (nonatomic,retain) NSTimer *timer;
@end

@implementation MYNewsShopOrderDetailsBaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kYQLS(@"订单详情");
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucceedAction) name:YJPaySucceedNotiKey object:nil];
    UIImage *rightImage = YQIMG(@"MY_nav_service_icon");
    self.rightItemImage = [rightImage qmui_imageWithTintColor:UIColor.whiteColor];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getDetailsData];

}

-(void)setupView {
    [super setupView];
    [self _setupNav];
    UIImage *leftImage = YQIMG(@"nav_back_sIcon");
    [self.leftItem setImage:[leftImage qmui_imageWithTintColor:UIColor.whiteColor] forState:(UIControlStateNormal)];
    [self.view addSubview:self.headerView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(104);
    }];
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    self.listTableView.frame = CGRectMake(0, 104, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-104-49);
    [self.view addSubview:self.listTableView];
    [self.view addSubview:self.bottonView];
    [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageGoodsCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderDetailsMoneyCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderDetailsLookLogisticsCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderDetailsInfoCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQGoodsScenicspotOrderDetailsCell")
    
    kYQREGISTERTABLEVIEWCHeaderFooter([YQOrderDetailsTitleHeader class])
    
    self.listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getDetailsData];
    }];
    YQSHOWLOADINGINVIEW;
}

-(void)getDetailsData {

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"orderId"] = self.orderModel.orderId;
    parameters[@"orderType"] = @(self.orderModel.orderType);
    
    
    [YQPNetWorkingManager sendPostRequest:kPOST_GOODS_ORDER_INFO_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        [self stopRefresh];
        if (responseObject.code == 0) {
            self.orderDetailsModel = [YQGoodsOrderDetailsModel modelWithJSON:responseObject.data];
            self.headerView.newsOrderModel = self.orderDetailsModel;
            self.bottonView.newsOrderModel = self.orderDetailsModel;
            if (self.orderDetailsModel.orderStatus == 201) {
                self.listTableView.frame = CGRectMake(0, 104, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-104);
                self.bottonView.hidden = YES;
            }
            self.goodsOrderModel = self.orderDetailsModel.orderItemList.firstObject;
            if (self.type == 2) {
                self.secondSectionTitle = self.goodsOrderModel.goodsName;
                self.thirdSectionTitle = kYQLS(@"住客信息");
                self.fourthSectionTitle = kYQLS(@"订单信息");
            }else if (self.type == 3){
                self.thirdSectionTitle = kYQLS(@"预定人信息");
                self.fourthSectionTitle = kYQLS(@"订单信息");
            }else{
                self.thirdSectionTitle = kYQLS(@"报名人信息");
                self.fourthSectionTitle = kYQLS(@"订单信息");
            }
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        [self stopRefresh];
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error);
    }];

    
}

#pragma -mark 私有
-(void)_setupNav {
    UIFont *font = kSystemMedium(17);
    NSDictionary *dic = @{ NSFontAttributeName:font,NSForegroundColorAttributeName:UIColor.whiteColor};
    self.navigationController.navigationBar.titleTextAttributes =dic;
    // 一行代码搞定导航栏颜色
    [self wr_setNavBarBarTintColor:kAPPThemeColor];
    // 一行代码搞定导航栏底部分割线是否隐藏
    [self wr_setNavBarShadowImageHidden:YES];
    [self wr_setNavBarTitleColor:[UIColor whiteColor]];
    [self wr_setNavBarTintColor:UIColor.whiteColor];
}

-(void)rightItemAction:(UIButton *)sender {
    
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return 1;
    }
    return 3;
}


- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {

        YQOrderManageGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageGoodsCell"];

        return goodsCell;
    }else if (indexPath.section == 1) {
        YQOrderDetailsMoneyCell *moneyCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderDetailsMoneyCell"];
        return moneyCell;
    }else if (indexPath.section == 2) {

    }
    
    YQOrderDetailsInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderDetailsInfoCell"];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 104;
    }else if (indexPath.section == 1){
        return 30;
    }else if (indexPath.section == 2) {
        return 44;
    }
    return 21;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [UIView new];
        view.backgroundColor = UIColor.whiteColor;
        return view;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 23.5;
    }
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 2 || section == 3 || section == 4) {
        YQOrderDetailsTitleHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"YQOrderDetailsTitleHeader"];
        if (section == 2) {
            header.titleLb.text = self.secondSectionTitle;
        }else if (section == 3) {
            header.titleLb.text = self.thirdSectionTitle;
        }else{
            header.titleLb.text = self.fourthSectionTitle;
        }
        return header;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 2 || section == 3 || section == 4) {
        return 39;
    }
    return 0.001;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end


#pragma makr -- lazy
-(YQOrderDetailsHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [YQOrderDetailsHeaderView viewFromXib];
        _headerView.topBgView.backgroundColor = kAPPThemeColor;
        _headerView.stateLb.text = kYQLS(@"确认收货");
        _headerView.timeLb.text = @"剩余: 05小时57小时";
        _headerView.nameLb.text = @"李晓冬";
        _headerView.phoneLb.text = @"17727956732";
        _headerView.locationLb.text = @"地址 : 广东省深圳市南山区蛇口街道创业一号C栋";
        _headerView.locationView.hidden = YES;
        _headerView.backgroundColor = kAPPThemeColor;
    }
    return _headerView;
}

-(YQOrderDetailsBottonView *)bottonView {
    if (!_bottonView) {
        _bottonView = [YQOrderDetailsBottonView viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        //2.设置阴影偏移范围
        _bottonView.layer.shadowOffset = CGSizeMake(0, 2);
        //3.设置阴影颜色的透明度
        _bottonView.layer.shadowOpacity = 0.5;
        
        //4.设置阴影半径
        _bottonView.layer.shadowRadius = 4;
        //5.设置阴影路径
        _bottonView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.navigationController.navigationBar.bounds].CGPath;
        [_bottonView.rightBtn setTitle:kYQLS(@"评价") forState:(UIControlStateNormal)];
        _bottonView.delegate = self;
    }
    return _bottonView;
}

#pragma makr -- lazy end
- (void)selectItem:(NSInteger)itme {
    
    switch (self.orderDetailsModel.orderStatus) {
        case 101:
            if(itme == 0){
               //取消订单
                QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:kYQLS(@"确定取消该订单?") message:@"" preferredStyle:(QMUIAlertControllerStyleAlert)];
                
                [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"我再想一想") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    
                }]];
                alert.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(17),NSKernAttributeName:@(0)};
                
                [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"确定") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    //取消订单
                    [self cancelActionOrder];
                }]];
                alert.alertButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0xB7B7B7),NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
                
                [alert showWithAnimated:YES];
            }else{
               //支付
                //立即支付
                [MYShopSalesOrderPayView shopSalesOrderPayView:[NSString stringWithFormat:@"%@",self.orderDetailsModel.payAmount] :^(NSInteger index, NSString * typeStr) {
                    
                    [self getOrderPayType:index orderId:self.orderDetailsModel.orderId orderType:[NSString stringWithFormat:@"%zd",self.orderDetailsModel.orderType]];
                    
                } :^{
                    NSLog(@"");
                }];
            }
            break;
        case 102:
        case 103:
        case 202:
            //删除
            [self deleteOrderAction];
            break;
        case 201:
            
            
            break;
        case 301:
        case 302:
        case 303:
            //发布评价
        {
            OrderEvaViewController *VC = [[OrderEvaViewController alloc] init];
            VC.orderModel = self.orderModel;
            [self.navigationController pushViewController:VC animated:true];
        }
            break;
        
        default:
            break;
    }
    

}



//删除订单
-(void)deleteOrderAction {

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"orderType"] = @(self.type);

    parameters[@"orderId"] = self.orderDetailsModel.orderId;
    YQSHOWLOADINGINVIEW;
    [YQPNetWorkingManager sendPostRequest:kPOST_BASE_ORDER_DELETE_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            YQUITIPSSUCCEED(responseObject.msg)
            [self.navigationController popViewControllerAnimated:true];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
        
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
    }];
}

//取消订单
-(void)cancelActionOrder{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"cancelOrderContent"] = @"";

    parameters[@"orderId"] = self.orderDetailsModel.orderId;;
    parameters[@"orderType"] = @(self.type);
    YQSHOWLOADINGINVIEW;
    [YQPNetWorkingManager sendPostRequest:kPOST_GOODS_ORDER_cancel_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            YQUITIPSSUCCEED(responseObject.msg)
            [self getDetailsData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
        
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
    }];
}
//支付
-(void)getOrderPayType:(NSInteger)type orderId:(NSString *)orderId orderType:(NSString *)orderType {
    NSMutableDictionary *par = @{}.mutableCopy;
    par[@"orderId"] = orderId;
    par[@"payType"] = @(type + 1);
    par[@"orderType"] = @"1";
    self.payParameters=par;
    NSString *url=kALIPAY_ALIPAYPAYREQUEST_URL;
       if (type==1)
       {
           url=kALIPAY_WECHATPAYPAYREQUEST_URL;
       }
    [YQPNetWorkingManager sendPostRequest:url parameters:par success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
           if (type == 0) {
                [self goToAlipayData:responseObject.data];
            }
            else
            {
                NSDictionary *dict=(NSDictionary*)responseObject.data;
                PayReq* req= [[PayReq alloc] init];
                req.openID=[dict objectForKey:@"appId"];
                req.partnerId= [dict objectForKey:@"partnerId"];
                req.prepayId= [dict objectForKey:@"prepayId"];
                req.nonceStr = [dict objectForKey:@"nonceStr"];
                req.timeStamp= [[dict objectForKey:@"timestamp"] intValue];
                req.package= [dict objectForKey:@"packageStr"];
                req.sign= [dict objectForKey:@"sign"];
                [WXApi sendReq:req completion:^(BOOL success) {
                    NSLog(@"1");
                }];
            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
    }];
}
-(void)goToAlipayData:(NSString *)dataStr{
    NSString *appScheme = @"com.MuYing.www";
    [[AlipaySDK defaultService] payOrder:dataStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        //网页支付回调
        NSNotificationCenter *notiCenter=[NSNotificationCenter defaultCenter];
        //NSLog(@"result = %@",resultDic);
        NSString *resultStatus = resultDic[@"resultStatus"];
        if ([resultDic[@"memo"] isEqualToString:@""] && [resultStatus isEqualToString:@"9000"]) {
            /*支付成功通知*/
            [notiCenter postNotificationName:YJPaySucceedNotiKey object:self userInfo:nil];
        }else{
            
            if ([resultStatus isEqualToString:@"6001"]) {
                /*用户取消了支付*/
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    MBErrHUD(kYQLS(@"支付已取消"));
                });
            }else{
                NSString * strMsg = [NSString stringWithFormat:@"%@：%@,%@",kYQLS(@"支付结果"),kYQLS(@"支付失败"),resultDic[@"memo"]];
                NSLog(@"strMsg: %@",strMsg);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }
    }];
}

-(void)paySucceedAction
{
   YQSHOWLOADINGINVIEW
   self.timer=[NSTimer scheduledTimerWithTimeInterval:2  target:self  selector:@selector(verifyPaymentResults) userInfo:nil  repeats:YES];
}

- (void)verifyPaymentResults
{
    [YQPNetWorkingManager sendPostRequest:kPAYRETURN parameters:self.payParameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            YQHIDELOADINGTIPS
            [self.timer invalidate];
            self.timer=nil;
            MYShopSalesOrderSucceedVC *succeedVC = [[MYShopSalesOrderSucceedVC alloc]initWithNibName:@"MYShopSalesOrderSucceedVC" bundle:nil];
            succeedVC.isIntegral = NO;
            succeedVC.navigationItem.title = kYQLS(@"支付成功");
            succeedVC.paySuceedLb.text = kYQLS(@"订单支付成功");
            succeedVC.paySuceedBtnText = kYQLS(@"查看我的订单");
            [self.navigationController pushViewController:succeedVC animated:true];
        }
        else if (responseObject.code==4) {
        }
        else
        {
                YQHIDELOADINGTIPS
                [self.timer invalidate];
                self.timer=nil;
                YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error)
        [self.timer invalidate];
        self.timer=nil;
    }];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
